var millName; //染厂名称
var millData = [];
var openID;
var hgS2;
var Judge_plan;
var Judge_metal;
var Judge_dye;
var code = getQueryString("code");

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}



$(function () {
    /*设置日期默认值*/
    var etime = new Date();
    $('#appDateTime').val(getDay(-7));
    $('#appDateTime02').val(getDay(0));

    /******************************************/

    //获取登录用户的权限和对应显示的数据
    getopenid();


    /**********************************************************/
});

function getopenid() {
    console.log(
        'https://www.xdfznh.club/wxpadbe/switch/oao/'
        + code);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/switch/oao/'
            + code,
        type: 'get',
        dataType: 'json',
        // 成功回调
        success: function (data) {
            console.log('请求成功');
            openID = data.data;
            console.log('openID=' + openID);
            getmill();
        },
        //失败回调
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //查看错误信息
            console.log('失败回调');
            console.log(XMLHttpRequest.status);
            console.log(XMLHttpRequest.readyState);
            console.log(textStatus);
        }
    })
}

//获取微信号对应的染厂名称
function getmill() {
    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/userMillController/selectMills/'
            + openID,

        type: 'get',
        dataType: 'json',
        success: function (data) {
            console.log(data.length);
            var ID;
            var liNodes = document.getElementsByTagName("input");
            if (data.length == 0) {
                // 关闭当前页面
                alert('当前用户没有权限！');

            }

            if (data.length > 0) {
                millName = data[0].mill;

                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                }
                ;
                getJurisdiction(); //获取个人查看报表的权限
                getDropDownDate(); // 设置下拉

            };
        }
    })
};

//获取个人查看报表的权限
function getJurisdiction() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);
    console.log(millName);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/perm/selectBoss/'
            + openID + '/'
            + millName,

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                millName = data[0].mill;
                var metal = eval('(' + data[0].rpt_metal + ')');  /*五金权限*/
                var dye = eval('(' + data[0].rpt_dye + ')');     /*染料权限*/

                if (metal) {
                    Judge_metal = true;
                    getData();
                    getsum();

                } else {
                    Judge_metal = false;
                    alert('当前用户没有查看五金仓库权限！');
                }
                if (dye) {
                    Judge_dye = true;
                    getData1();
                    getsum();
                } else  {
                    Judge_dye = false;
                    alert('当前用户没有查看染料仓库权限！');
                }

                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                }
                ;
                // console.log(millData);

                getDropDownDate(); // 设置下拉

            } else {
                Judge_metal = false;
                Judge_dye = false;
                alert('当前用户没有查看报表权限！');
            };
        }
    })

};

// 染料仓库
function getData() {

    var data1=document.getElementById("appDateTime").value.substr(0, 10);
    var data2=document.getElementById("appDateTime02").value.substr(0, 10);

    if (timeFn(data1,data2)>31){
        alert('当前查询日期区间大于一个月，不可查询五金仓库！');
        return;
    }

    // console.log('https://www.xdfznh.club/wxpadbe/execute/query/'
    //     + millName + '/'
    //     + "call hardwareDetail('"
    //     + data1
    //     +"','"
    //     + data2
    //     + "')"
    // );

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName + '/'
            + "call hardwareDetail('"
            + data1
            +"','"
            + data2
            + "')",

        type: 'get',
        dataType: 'json',
        success: function (data) {
            $('#waterdetai02').datagrid('loadData', data);
            //getsum();
        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
            getsum();
        }
    })
};

//五金仓库
function getData1() {
    var data1=document.getElementById("appDateTime").value.substr(0, 10);
    var data2=document.getElementById("appDateTime02").value.substr(0, 10);

    if (timeFn(data1,data2)>31){
        alert('当前查询日期区间大于一个月，不可查询染料仓库！');
        return;
    }

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe/execute/query/'
            + millName + '/'
            + "call MetalInventory('"
            + document.getElementById("appDateTime").value
            +"','"
            + document.getElementById("appDateTime02").value
            + "')",

        // url: 'https://www.xdfznh.club/wxpadbe/dynamicDS/query'
        //     + "/call MetalInventory('"
        //     + millName + "','"
        //     + document.getElementById("appDateTime").value + "','"
        //     + document.getElementById("appDateTime02").value + "')",

        type: 'get',
        dataType: 'json',
        success: function (data) {
            $('#waterdetai01').datagrid('loadData', data);
        },
        complete: function(XMLHttpRequest, textStatus) {
            $(".buttom").attr("disabled",false);
            getsum();
        }
    })
};

function getsum() {
    /*表格数据求和*/

    //五金
    $('#waterdetai01').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var rk = 0;
            var ck=0;
            var kc=0;
            for (let i = 0; i < data.length; i++) {
                rk += data[i].RKqty ? parseFloat(data[i].RKqty) : 0;
                ck += data[i].CKqty ? parseFloat(data[i].CKqty) : 0;
                kc += data[i].KCqty ? parseFloat(data[i].KCqty) : 0;
            }
            $(this).datagrid('reloadFooter', [{
                metal_name: '合计',
                RKqty: rk.toFixed(1),
                CKqty: ck.toFixed(1),
                KCqty: kc.toFixed(1)
            }])
        }
    });

    //染料
    $('#waterdetai02').datagrid({
        showFooter:true,
        onLoadSuccess: function (data) {
            data = data.rows;
            var rk = 0;
            var ck=0;
            var kc=0;
            for (let i = 0; i < data.length; i++) {
                rk += data[i].b_rkqty ? parseFloat(data[i].b_rkqty) : 0;
                ck += data[i].b_ckqty ? parseFloat(data[i].b_ckqty) : 0;
                kc += data[i].b_kcqty ? parseFloat(data[i].b_kcqty) : 0;
            }
            $(this).datagrid('reloadFooter', [{
                goodsName: '合计',
                b_rkqty: rk.toFixed(1),
                b_ckqty: ck.toFixed(1),
                b_kcqty: kc.toFixed(1)
            }])
        }
    })

};

//查询事件
function getquery() {
    if (Judge_metal == true) {
        getData();
    }
    if (Judge_dye == true) {
        getData1();
    }
}

/******************************************************************************************/

/*设置时间格式*/
function add0(m) {
    return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

formatterSDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + day ; //+ " " + "07" + ":" + "00"
};

formatterEDate = function (date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    var hor = date.getHours()> 9 ? date.getHours() : "0" + date.getHours();
    var min = date.getMinutes()> 9 ? date.getMinutes() : "0" + date.getMinutes();;
    var sec = date.getSeconds();
    return date.getFullYear() + '-' + month + '-' + day ;  //+ " " + hor + ":" + "00"
};


/*****************************************************************************************/

/*自定义本月日期时间*/
customSDateMonth = function (date) {
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
    return date.getFullYear() + '-' + month + '-' + "01" ;  //+ " " + "07" + ":" + "00"
};

//计算当前日期的前后几天的日期
function getDay(day){
    var today = new Date();
    var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
    today.setTime(targetday_milliseconds); //注意，这行是关键代码
    var tYear = today.getFullYear();
    var tMonth = today.getMonth();
    var tDate = today.getDate();
    tMonth = doHandleMonth(tMonth + 1);
    tDate = doHandleMonth(tDate);
    return tYear+"-"+tMonth+"-"+tDate ;  //+ " " + "07" + ":" + "00"
}

function doHandleMonth(month){
    var m = month;
    if(month.toString().length == 1){
        m = "0" + month;
    }
    return m;
}

/*查询一天的日期设置*/
function getdaydate() {
    var etime = new Date();
    $('#appDateTime').val(getDay(-1));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}
/*查询一周的日期设置*/
function getWeekdate() {
    var etime =new Date();
    $('#appDateTime').val(getDay(-7));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}
/*查询一个月的日期设置*/
function getOneMonthdate() {
    var etime =new Date();
    $('#appDateTime').val(getDay(-30));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}

/*查询本月的日期设置*/
function getMonthdate() {
    var etime = new Date();
    $('#appDateTime').val(customSDateMonth(etime));
    $('#appDateTime02').val(formatterSDate(etime));

    getquery();
}


/********************************************************************************/
/*获取标签的序号*/
function getTabSelectedIndex() {
    return $('#tabs').tabs('getTabIndex', $('#tabs').tabs('getSelected'));
}

//获取当前所选中标签的序号，打开对应的图形信息
function getClientName() {
    if (Judge_plan == true) {
        var SDate = document.getElementById("appDateTime").value;
        var EDate = document.getElementById("appDateTime02").value;
        var strhref;
        switch (getTabSelectedIndex()) {
            case 0:
                strhref = "html/wx_image_detail.html"
                    + '?'
                    + 'SDate=' + SDate
                    + '&'
                    + 'EDate=' + EDate
                    + '&'
                    + 'ybname=' + '天然气'
                    + '&'
                    + 'millname=' + millName;

                location.href = strhref;
                // $("#imagedetable").attr("href",strhref);
                break;

            case 1:
                strhref = "html/wx_image_detail.html"
                    + '?'
                    + 'SDate=' + SDate
                    + '&'
                    + 'EDate=' + EDate
                    + '&'
                    + 'ybname=' + '水表'
                    + '&'
                    + 'millname=' + millName;

                location.href = strhref;
                // $("#imagedetable").attr("href",strhref);
                break;
            case 2:
                strhref = "html/wx_image_detail.html"
                    + '?'
                    + 'SDate=' + SDate
                    + '&'
                    + 'EDate=' + EDate
                    + '&'
                    + 'ybname=' + '电表'
                    + '&'
                    + 'millname=' + millName;

                location.href = strhref;
                //$("#imagedetable").attr("href",strhref);
                break;
            case 3:
                strhref = "html/wx_image_detail.html"
                    + '?'
                    + 'SDate=' + SDate
                    + '&'
                    + 'EDate=' + EDate
                    + '&'
                    + 'ybname=' + '蒸汽'
                    + '&'
                    + 'millname=' + millName;

                location.href = strhref;
                //$("#imagedetable").attr("href",strhref);
                break;
        }
    }

}


//设置染厂下拉
function getDropDownDate() {
    console.log('2=' + millData);
    hgS2 = new selectSwiper({
        el: '.select_box2',
        mustSelect: true,
        activeIndex: 0,
        data: millData,
        init: function (index) {
            if (index !== -1) {
                $('.btn2').html(this.data[index]);
            }
        },
        okFunUndefind: function () {
            alert('必须选择一项');
        },
        okFun: function (index) {
            $('.btn2').html(this.data[index]);
            millName = $('button').text();
            getJurisdictionmill();

        },
        closeFun: function () {
            console.log('取消');
        },
    });

    $('.btn2').on('click', function () {
        hgS2.openSelectSwiper();

    });
}

//在更换染厂之后  重新刷新数据  并判断个人权限
function getJurisdictionmill() {
    console.log('https://www.xdfznh.club/wxpadbe'
        + '/perm/selectBoss/'
        + openID + '/'
        + millName);

    $.ajax({
        url: 'https://www.xdfznh.club/wxpadbe'
            + '/perm/selectBoss/'
            + openID + '/'
            + millName,

        type: 'get',
        dataType: 'json',
        success: function (data) {

            if (data.length > 0) {
                millName = data[0].mill;
                var metal = eval('(' + data[0].rpt_metal + ')');  /*五金权限*/
                var dye = eval('(' + data[0].rpt_dye + ')');     /*染料权限*/

                if (metal) {
                    Judge_metal = true;
                    getData();
                    getsum()
                } else {
                    Judge_metal = false;
                    alert('当前用户没有查看五金仓库权限！');
                }
                if (dye) {
                    Judge_dye = true;
                    getData1();
                    getsum()
                } else  {
                    Judge_dye = false;
                    alert('当前用户没有查看染料仓库权限！');
                }

                for (var n = 0; n < data.length; n++) {
                    millData[n] = data[n].mill;
                    console.log(data[n].mill);
                }
                ;
                // console.log(millData);
                getDropDownDate(); // 设置下拉

            } else {
                Judge_metal = false;
                Judge_dye = false;
                alert('当前用户没有查看报表权限！');
            };
        }
    })

}


/*计算两个时间差*/
function timeFn(d1,d2) {//di作为一个变量传进来
//如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
    var dateBegin = new Date(d1.replace(/-/g, "/"));//将-转化为/，使用new Date
    var dateEnd =  new Date(d2.replace(/-/g, "/"));//将-转化为/，使用new Date
    var dateDiff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数
    var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));//计算出相差天数
    var leave1=dateDiff%(24*3600*1000) //计算天数后剩余的毫秒数
    var hours=Math.floor(leave1/(3600*1000))//计算出小时数
//计算相差分钟数
    var leave2=leave1%(3600*1000) //计算小时数后剩余的毫秒数
    var minutes=Math.floor(leave2/(60*1000))//计算相差分钟数
//计算相差秒数
    var leave3=leave2%(60*1000) //计算分钟数后剩余的毫秒数
    var seconds=Math.round(leave3/1000)
    //console.log(" 相差 "+dayDiff+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
    //console.log(dateDiff+"时间差的毫秒数",dayDiff+"计算出相差天数",leave1+"计算天数后剩余的毫秒数"
    //   ,hours+"计算出小时数",minutes+"计算相差分钟数",seconds+"计算相差秒数");

    return Math.abs(dayDiff);
}


function  CleanupGrid(){
    var data=[];
    $('#waterdetai').datagrid('loadData', data);
    $('#waterdetai02').datagrid('loadData', data);
}